package main

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/xml"
	"fmt"
	"github.com/astaxie/beego"
	"io"
	"io/ioutil"
	"net/http"
	"sort"
	"time"
)

const token = "fancg"

type hello struct {
	beego.Controller
}

func (h *hello) Hello() {
	h.Data["json"] = "hello"
	h.ServeJSON()
}

//func main(){
//	beego.Router("/",&hello{},"*:Hello")
//	beego.Run()
//}
type Message struct {
	ToUserName   string
	FromUserName string
	CreateTime   int
	MsgType      string
	Content      string
	MsgId        string
}

func index(w http.ResponseWriter, r *http.Request) {
	url := r.RequestURI
	fmt.Println(url)

	method := r.Method
	fmt.Println(method)
	if method == "POST" {
		bytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			println(err)
		}
		var message Message
		err = xml.Unmarshal(bytes, &message)
		if err != nil {
			fmt.Println(string(bytes))
		}
		defer r.Body.Close()
		t := time.Now()
		reply := fmt.Sprintf("<xml>"+
			"<ToUserName><![CDATA[%s]]></ToUserName>"+
			"<FromUserName><![CDATA[%s]]></FromUserName> "+
			"<CreateTime>%d</CreateTime>"+
			"<MsgType><![CDATA[text]]></MsgType>"+
			"<Content><![CDATA[%s]]></Content>"+
			"</xml>", message.FromUserName, message.ToUserName, t.Unix(), message.Content)
		fmt.Println(reply)
		io.WriteString(w, reply)
		return
	} else {
		r.ParseForm()
		signature := r.Form["signature"][0]
		echostr := r.Form["echostr"][0]
		timestamp := r.Form["timestamp"][0]
		nonce := r.Form["nonce"][0]
		fmt.Printf("signature:%v,echostr:%v,timestamp:%v,nonce:%v", signature, echostr, timestamp, nonce)

		tmpArr := []string{token, timestamp, nonce}
		sort.Strings(tmpArr)

		var tmpStr = ""
		for _, item := range tmpArr {
			for _, v := range item {
				tmpStr = tmpStr + string(v)
			}
		}

		shaStr := Sha1(tmpStr)

		if shaStr == signature {
			io.WriteString(w, echostr)
		} else {
			io.WriteString(w, "error")
		}

	}

}
func Sha1(data string) string {
	sha1 := sha1.New()
	sha1.Write([]byte(data))
	return hex.EncodeToString(sha1.Sum([]byte("")))
}

//curl "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c9f350941f2452e&secret=c918a9a670e93ad83026b6a2f92d9b5b"

func Token(w http.ResponseWriter, r *http.Request) {
	resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c9f350941f2452e&secret=c918a9a670e93ad83026b6a2f92d9b5b")
	if err != nil {
		fmt.Printf("err:%v", err)
	}
	defer resp.Body.Close()
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("err:%v", err)
	}
	io.WriteString(w, string(bytes))
}

//func main() {
//	http.HandleFunc("/signa", index)
//	http.HandleFunc("/token", Token)
//	if err := http.ListenAndServe(":80", nil); err != nil {
//		log.Fatal("ListenAndServe:", err)
//	}
//
//}
